package com.dman.multi.core;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;

public class DownloadSpeed {
	private static final int SPEED_ITERATIONS = 5;
	private long startTimeNano;
	private long currTimeNano;
	private ArrayBlockingQueue<Long> bytesRead;
	private ArrayBlockingQueue<Long> timeBytesRead;
	
	public DownloadSpeed() {
		startTimeNano = System.nanoTime();
		currTimeNano = startTimeNano;
		bytesRead = new ArrayBlockingQueue<Long>(SPEED_ITERATIONS);
		timeBytesRead = new ArrayBlockingQueue<Long>(SPEED_ITERATIONS);
	}
	
	public double measureSpeed(){
		double downloadSpeed = 0.0;
		if(bytesRead.remainingCapacity() == 0){
			int sum = 0;
			Iterator<Long> iterBytesRead = bytesRead.iterator();
			Iterator<Long> iterTimeBytesRead = timeBytesRead.iterator();
			while(iterBytesRead.hasNext() && iterTimeBytesRead.hasNext()){
				sum += iterBytesRead.next();
				currTimeNano = iterTimeBytesRead.next();
			}
			startTimeNano = timeBytesRead.remove();
			sum -= bytesRead.remove();
			downloadSpeed = 1000000000.0 * sum / (currTimeNano - startTimeNano);
		}
		
		return downloadSpeed;
	}
	
	public void addData(long readBytes){
		bytesRead.add(readBytes);
		timeBytesRead.add(System.nanoTime());
	}
}
